import io
from datetime import timezone

import requests.utils
from django.contrib.auth.models import User
from django.shortcuts import render
from django.views import View
from django.http import HttpResponse
from django_redis import get_redis_connection
from rest_framework import status
from rest_framework.response import Response
from rest_framework.viewsets import ModelViewSet
from rest_framework_simplejwt.serializers import TokenObtainPairSerializer
from rest_framework_simplejwt.views import TokenObtainPairView

from user.models import ImageVerifyCode
from user.serializers import UserSerializer, MyTokenObtainPairSerializer
from utils.verifyUtil import ImageVerifyUtil


# Create your views here.

class ImageVerifyView(View):
    def get(self, request, uuid, func):
        """
        返回验证码图片
        :param request:
        :return:
        """
        imageVerify = ImageVerifyUtil()
        img, code = imageVerify.verify_image()

        # 生成一个临时文件
        img_bytes = io.BytesIO()
        img.save(img_bytes, format='PNG')
        img_bytes = img_bytes.getvalue()
        # 把答案保存到数据库中
        try:
            # 修改后的存储逻辑
            ImageVerifyCode.objects.update_or_create(
                uuid=uuid,
                func=func,
                defaults={'code': code}  # 更新 code 和时间戳
            )
        except Exception as e:
            print(e)
        # 返回字节数据，指定类型为png
        return HttpResponse(img_bytes, content_type='image/png')


class UserViewSet(ModelViewSet):
    queryset = User.objects.all()
    serializer_class = UserSerializer

    def create(self, request, *args, **kwargs):
        serializer = self.get_serializer(data=request.data)
        serializer.is_valid(raise_exception=True)
        # 得到用户传入的数据
        username = request.data.get('username')
        password = request.data.get('password')
        # 创建用户对象，并保存
        user = User(username=username)
        user.set_password(password)
        user.save()
        return Response(serializer.data, status=status.HTTP_201_CREATED)


class MyTokenObtainPairView(TokenObtainPairView):
    serializer_class = MyTokenObtainPairSerializer